<script setup lang="ts">
import { ref, computed } from 'vue'
import { Picture, Download } from '@element-plus/icons-vue'
import { useImageStore } from '@/stores/image'
import { useRouter } from 'vue-router'
import { getFullStaticUrl, ocrRecognition } from '@/api'
import { ElMessage } from 'element-plus'

const router = useRouter()
const imageStore = useImageStore()
const loadingOcr = ref(false)

const markedImageUrl = computed(() => {
  if (!imageStore.detectionResult?.marked_image_url) return ''
  const url = getFullStaticUrl(imageStore.detectionResult.marked_image_url)
  console.log('标注图片URL:', url)
  return url
})

const vehicleMarkedImageUrl = computed(() => {
  if (!imageStore.detectionResult?.vehicle_marked_image_url) return ''
  const url = getFullStaticUrl(imageStore.detectionResult.vehicle_marked_image_url)
  console.log('车辆标注图片URL:', url)
  return url
})

const croppedPlateUrl = computed(() => {
  if (!imageStore.detectionResult?.cropped_plate_url) return ''
  const url = getFullStaticUrl(imageStore.detectionResult.cropped_plate_url)
  console.log('裁剪车牌URL:', url)
  return url
})

const ocrResImgUrl = computed(() => {
  if (!imageStore.detectionResult?.ocr_res_img_url) return ''
  const url = getFullStaticUrl(imageStore.detectionResult.ocr_res_img_url)
  console.log('OCR识别结果图片URL:', url)
  return url
})

// 判断是否是联合检测结果
const isJointDetection = computed(() => {
  return !!imageStore.detectionResult?.plate_detections && !!imageStore.detectionResult?.vehicle_detections
})

// 判断是否是多辆车检测结果
const isMultiVehicleDetection = computed(() => {
  return imageStore.detectionResult?.model_name === '多辆车检测模型' && 
         !!imageStore.detectionResult?.detection_results && 
         imageStore.detectionResult.detection_results.length > 1
})

const handleDownloadMarkedImage = () => {
  if (!imageStore.detectionResult?.marked_image_url) return
  
  // 从URL中提取文件名
  const urlParts = imageStore.detectionResult.marked_image_url.split('/')
  const fileName = urlParts[urlParts.length - 1]
  
  const link = document.createElement('a')
  link.href = markedImageUrl.value
  link.download = `车牌检测结果_${imageStore.detectionResult.license_plate_text || '未知'}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const handleBackToUpload = () => {
  router.push('/upload')
}

const handleOcrRecognition = async () => {
  if (!imageStore.detectionResult?.cropped_plate_url) {
    ElMessage.warning('没有可用的车牌图片')
    return
  }
  
  loadingOcr.value = true
  try {
    // 获取车牌图片路径，与其他函数保持一致的处理方式
    let croppedPlatePath = imageStore.detectionResult.cropped_plate_url
    
    // 如果是完整URL，转换为相对路径
    if (croppedPlatePath.startsWith('http://localhost:5000')) {
      croppedPlatePath = croppedPlatePath.replace('http://localhost:5000', '')
    }
    
    // 将/static/前缀替换为uploads/，以匹配后端API期望的路径格式
    if (croppedPlatePath.startsWith('/static/')) {
      croppedPlatePath = croppedPlatePath.replace('/static/', 'uploads/')
    }
    
    console.log('开始OCR识别，车牌图片路径:', croppedPlatePath)
    const res = await ocrRecognition(croppedPlatePath)
    
    if (res && res.plate_text) {
      // 更新检测结果中的OCR相关字段
      if (imageStore.detectionResult) {
        imageStore.setDetectionResult({
          ...imageStore.detectionResult,
          ocr_plate_text: res.plate_text,
          ocr_confidence: res.ocr_confidence,
          ocr_res_img_url: res.ocr_res_img_url
        })
      }
      ElMessage.success('OCR识别成功')
    } else {
      throw new Error('OCR识别响应格式不正确')
    }
  } catch (e: any) {
    console.error('OCR识别错误详情:', e)
    const errorMsg = e.response?.data?.error || e.message || 'OCR识别失败'
    ElMessage.error(errorMsg)
  } finally {
    loadingOcr.value = false
  }
}

const handleDownloadOcrImage = () => {
  if (!imageStore.detectionResult?.ocr_res_img_url) return
  
  const link = document.createElement('a')
  link.href = ocrResImgUrl.value
  link.download = `OCR识别结果_${imageStore.detectionResult.ocr_plate_text || '未知'}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<template>
  <div class="result-view">
    <!-- 标注结果卡片 -->
    <el-card class="section-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>检测标注结果</span>
          <el-button type="primary" link @click="handleBackToUpload">
            重新上传图片
          </el-button>
        </div>
      </template>
      <template v-if="imageStore.detectionResult?.marked_image_url">
        <!-- 多辆车检测结果展示 -->
        <template v-if="isMultiVehicleDetection">
          <div class="image-container">
            <h3>多辆车检测结果</h3>
            <el-image 
              :src="markedImageUrl" 
              fit="contain" 
              class="preview-img"
              @error="(e: Event) => console.error('图片加载错误:', markedImageUrl, e)"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                  <div>URL: {{ markedImageUrl }}</div>
                </div>
              </template>
            </el-image>
          </div>
          
          <!-- 多辆车检测统计信息 -->
          <el-card class="result-card" shadow="never">
            <div class="result-label">检测结果：</div>
            <el-text class="plate-text" type="primary">
              检测到 {{ imageStore.detectionResult.vehicle_count }} 辆车
            </el-text>
            <div class="confidence-info">
              <el-text type="info" size="small">
                检测置信度：{{ (imageStore.detectionResult.overall_accuracy! * 100).toFixed(1) }}%
              </el-text>
            </div>
          </el-card>
        </template>
        
        <!-- 联合检测结果展示 -->
        <template v-else-if="isJointDetection">
          <div class="image-container">
            <h3>车辆-车牌联合检测结果</h3>
            <el-image 
              :src="markedImageUrl" 
              fit="contain" 
              class="preview-img"
              @error="(e: Event) => console.error('图片加载错误:', markedImageUrl, e)"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                  <div>URL: {{ markedImageUrl }}</div>
                </div>
              </template>
            </el-image>
          </div>

          <!-- 车牌识别结果卡片 -->
          <el-card 
            v-if="imageStore.detectionResult.license_plate_text" 
            class="result-card" 
            shadow="never"
          >
            <div class="result-label">车牌识别结果：</div>
            <el-text class="plate-text" type="primary">
              {{ imageStore.detectionResult.license_plate_text }}
            </el-text>
            <div class="confidence-info">
              <el-text type="info" size="small">
                车牌识别置信度：{{ (imageStore.detectionResult.plate_accuracy! * 100).toFixed(1) }}%
              </el-text>
            </div>
          </el-card>
        </template>
        
        <!-- 车辆检测图片显示（非联合检测结果） -->
        <div v-else-if="vehicleMarkedImageUrl" class="image-container">
          <h3>车辆检测结果</h3>
          <el-image 
            :src="vehicleMarkedImageUrl" 
            fit="contain" 
            class="preview-img"
            @error="(e: Event) => console.error('车辆图片加载错误:', vehicleMarkedImageUrl, e)"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                <span>车辆图片加载失败</span>
              </div>
            </template>
          </el-image>
        </div>
        
        <!-- 车牌检测图片显示（非联合检测结果） -->
        <div v-if="!isJointDetection && !isMultiVehicleDetection" class="image-container">
          <h3>车牌检测结果</h3>
          <el-image 
            :src="markedImageUrl" 
            fit="contain" 
            class="preview-img"
            @error="(e: Event) => console.error('图片加载错误:', markedImageUrl, e)"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
                <div>URL: {{ markedImageUrl }}</div>
              </div>
            </template>
          </el-image>
        </div>
        
        <!-- 车牌切片图片显示 -->
        <div v-if="croppedPlateUrl && !isJointDetection && !isMultiVehicleDetection" class="image-container">
          <h3>车牌切片结果</h3>
          <el-image 
            :src="croppedPlateUrl" 
            fit="contain" 
            class="plate-img"
            @error="(e: Event) => console.error('车牌图片加载错误:', croppedPlateUrl, e)"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                <span>车牌图片加载失败</span>
              </div>
            </template>
          </el-image>
          
          <!-- OCR识别按钮 -->
          <div class="ocr-actions" v-if="!imageStore.detectionResult.ocr_plate_text">
            <el-button 
              type="primary" 
              size="small" 
              :loading="loadingOcr"
              @click="handleOcrRecognition"
            >
              进行OCR识别
            </el-button>
          </div>
        </div>
        
        <!-- OCR识别结果显示 -->
        <div v-if="imageStore.detectionResult.ocr_plate_text && ocrResImgUrl && !isJointDetection && !isMultiVehicleDetection" class="image-container">
          <h3>OCR识别结果</h3>
          <el-image 
            :src="ocrResImgUrl" 
            fit="contain" 
            class="plate-img"
            @error="(e: Event) => console.error('OCR结果图片加载错误:', ocrResImgUrl, e)"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
                <span>OCR结果图片加载失败</span>
              </div>
            </template>
          </el-image>
          
          <el-card class="ocr-result-card" shadow="never">
            <div class="result-label">OCR识别结果：</div>
            <el-text class="plate-text" type="primary">
              {{ imageStore.detectionResult.ocr_plate_text }}
            </el-text>
            <div v-if="imageStore.detectionResult.ocr_confidence" class="confidence-info">
              <el-text type="info" size="small">
                OCR识别置信度：{{ (imageStore.detectionResult.ocr_confidence * 100).toFixed(1) }}%
              </el-text>
            </div>
          </el-card>
          
          <!-- 下载OCR结果图片按钮 -->
          <div class="ocr-actions">
            <el-button 
              type="success" 
              size="small" 
              @click="handleDownloadOcrImage"
            >
              <el-icon class="el-icon--download"><Download /></el-icon>
              下载OCR结果图片
            </el-button>
          </div>
        </div>
        
        <el-card 
          v-if="imageStore.detectionResult.license_plate_text && imageStore.detectionResult.license_plate_text !== '未识别车牌' && !isJointDetection && !isMultiVehicleDetection" 
          class="result-card" 
          shadow="never"
        >
          <div class="result-label">识别结果：</div>
          <el-text class="plate-text" type="primary">
            {{ imageStore.detectionResult.license_plate_text }}
          </el-text>
          <div v-if="imageStore.detectionResult.confidence" class="confidence-info">
            <el-text type="info" size="small">
              识别置信度：{{ (imageStore.detectionResult.confidence * 100).toFixed(1) }}%
            </el-text>
          </div>
        </el-card>
        <el-button
          type="primary"
          plain
          class="download-btn"
          @click="handleDownloadMarkedImage"
        >
          <el-icon class="el-icon--download"><Download /></el-icon>
          下载标注图片
        </el-button>
      </template>
      <el-empty
        v-else
        class="image-empty"
        description="请先完成检测"
      >
        <template #image>
          <el-icon :size="48" color="#909399"><Picture /></el-icon>
        </template>
        <template #default>
          <el-button type="primary" @click="router.push('/preprocess')">
            去进行检测
          </el-button>
        </template>
      </el-empty>
    </el-card>

    <!-- 检测结果详情 -->
    <el-card v-if="imageStore.detectionResult?.marked_image_url" class="stats-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>检测结果汇总</span>
        </div>
      </template>
      
      <!-- 基本统计信息 -->
      <el-descriptions :column="2" border>
        <el-descriptions-item label="模型运行时间">
          {{ imageStore.detectionResult.model_runtime ? `${imageStore.detectionResult.model_runtime} ms` : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="检测到的车辆数量">
          {{ imageStore.detectionResult.vehicle_count ?? '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="整体检测精度">
          {{ imageStore.detectionResult.overall_accuracy ? 
            `${(imageStore.detectionResult.overall_accuracy * 100).toFixed(1)}%` : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item v-if="isJointDetection" label="车牌检测精度">
          {{ imageStore.detectionResult.plate_accuracy ? 
            `${(imageStore.detectionResult.plate_accuracy * 100).toFixed(1)}%` : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item v-if="isJointDetection" label="车辆检测精度">
          {{ imageStore.detectionResult.vehicle_accuracy ? 
            `${(imageStore.detectionResult.vehicle_accuracy * 100).toFixed(1)}%` : '未知' }}
        </el-descriptions-item>
        <el-descriptions-item v-if="isJointDetection" label="检测到的车牌数量">
          {{ imageStore.detectionResult.plate_count ?? '未知' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 多辆车检测结果表格 -->
      <div 
        v-if="isMultiVehicleDetection && imageStore.detectionResult.detection_results?.length" 
        class="detection-table"
      >
        <div class="table-title">多辆车检测结果</div>
        <el-table 
          :data="imageStore.detectionResult.detection_results" 
          style="width: 100%" 
          border
          :max-height="400"
        >
          <el-table-column prop="type" label="对象类型" min-width="80" />
          <el-table-column prop="class" label="类别" min-width="80" />
          <el-table-column prop="confidence" label="置信度" min-width="100">
            <template #default="scope">
              {{ (scope.row.confidence * 100).toFixed(1) }}%
            </template>
          </el-table-column>
          <el-table-column label="位置信息" min-width="280">
            <template #default="scope">
              <el-text type="info" size="small">
                X: {{ Math.round(scope.row.bbox[0]) }} | Y: {{ Math.round(scope.row.bbox[1]) }} | 
                宽: {{ Math.round(scope.row.bbox[2] - scope.row.bbox[0]) }} | 高: {{ Math.round(scope.row.bbox[3] - scope.row.bbox[1]) }}
              </el-text>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 联合检测结果表格 -->
      <template v-else-if="isJointDetection">
        <!-- 车辆检测结果表格 -->
        <div 
          v-if="imageStore.detectionResult.vehicle_detections?.length" 
          class="detection-table"
        >
          <div class="table-title">车辆检测结果</div>
          <el-table 
            :data="imageStore.detectionResult.vehicle_detections" 
            style="width: 100%" 
            border
          >
            <el-table-column prop="type" label="对象类型" min-width="100" />
            <el-table-column prop="class" label="类别" min-width="120" />
            <el-table-column prop="confidence" label="置信度" min-width="100">
              <template #default="scope">
                {{ (scope.row.confidence * 100).toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column label="位置信息" min-width="280">
              <template #default="scope">
                <el-text type="info" size="small">
                  X: {{ Math.round(scope.row.bbox[0]) }} | Y: {{ Math.round(scope.row.bbox[1]) }} | 
                  宽: {{ Math.round(scope.row.bbox[2]) }} | 高: {{ Math.round(scope.row.bbox[3]) }}
                </el-text>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 车牌检测结果表格 -->
        <div 
          v-if="imageStore.detectionResult.plate_detections?.length" 
          class="detection-table"
        >
          <div class="table-title">车牌检测结果</div>
          <el-table 
            :data="imageStore.detectionResult.plate_detections" 
            style="width: 100%" 
            border
          >
            <el-table-column prop="type" label="对象类型" min-width="80" />
            <el-table-column prop="plate_text" label="车牌号" min-width="120" />
            <el-table-column prop="confidence" label="检测置信度" min-width="100">
              <template #default="scope">
                {{ (scope.row.confidence * 100).toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column prop="ocr_confidence" label="OCR置信度" min-width="100">
              <template #default="scope">
                {{ (scope.row.ocr_confidence * 100).toFixed(1) }}%
              </template>
            </el-table-column>
            <el-table-column label="位置信息" min-width="280">
              <template #default="scope">
                <el-text type="info" size="small">
                  X: {{ Math.round(scope.row.bbox[0]) }} | Y: {{ Math.round(scope.row.bbox[1]) }} | 
                  宽: {{ Math.round(scope.row.bbox[2]) }} | 高: {{ Math.round(scope.row.bbox[3]) }}
                </el-text>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>

      <!-- 常规检测结果表格 -->
      <div 
        v-else-if="imageStore.detectionResult.detection_results?.length" 
        class="detection-table"
      >
        <div class="table-title">检测对象详细信息</div>
        <el-table 
          :data="imageStore.detectionResult.detection_results" 
          style="width: 100%" 
          border
        >
          <el-table-column prop="type" label="对象类型" min-width="100" />
          <el-table-column prop="content" label="识别内容" min-width="120">
            <template #default="scope">
              {{ scope.row.content || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="confidence" label="置信度" min-width="100">
            <template #default="scope">
              {{ (scope.row.confidence * 100).toFixed(1) }}%
            </template>
          </el-table-column>
          <el-table-column label="位置信息" min-width="280">
            <template #default="scope">
              <el-text type="info" size="small">
                X: {{ scope.row.bbox[0] }} | Y: {{ scope.row.bbox[1] }} | 
                宽: {{ scope.row.bbox[2] }} | 高: {{ scope.row.bbox[3] }}
              </el-text>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 车牌识别结果表格 -->
      <div 
        v-if="imageStore.detectionResult.plates?.length && !isJointDetection && !isMultiVehicleDetection" 
        class="plates-table"
      >
        <div class="table-title">识别到的车牌列表</div>
        <el-table 
          :data="imageStore.detectionResult.plates" 
          style="width: 100%" 
          border
        >
          <el-table-column prop="text" label="车牌号" min-width="120" />
          <el-table-column prop="confidence" label="识别置信度" min-width="120">
            <template #default="scope">
              {{ (scope.row.confidence * 100).toFixed(1) }}%
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.result-view {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.section-card,
.stats-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-card:hover,
.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.preview-img {
  width: 100%;
  height: 240px;
  object-fit: contain;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.image-info {
  margin: 8px 0;
  text-align: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
}

.image-empty {
  height: 240px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  border-radius: 10px;
  margin-bottom: 14px;
}

.result-card {
  margin: 16px auto;
  width: 95%;
  min-height: 56px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f4faff;
  border-radius: 10px;
  border: none;
}

.result-label {
  font-size: 16px;
  color: #666;
  margin-bottom: 6px;
}

.plate-text {
  font-size: 1.5rem;
  color: #409EFF;
  font-weight: 700;
  letter-spacing: 2px;
}

.confidence-info {
  margin-top: 8px;
  text-align: center;
}

.download-btn {
  margin: 12px auto;
  width: 95%;
  display: block;
  --el-button-bg-color: transparent;
  --el-button-border-color: var(--primary-color);
  --el-button-text-color: var(--primary-color);
  --el-button-hover-text-color: var(--primary-color);
  --el-button-hover-bg-color: var(--primary-light);
  --el-button-hover-border-color: var(--primary-color);
  height: 40px;
  font-size: 14px;
}

.download-btn :deep(.el-icon) {
  margin-right: 8px;
  font-size: 16px;
  vertical-align: middle;
}

.download-btn:hover {
  color: var(--primary-color);
  background-color: var(--primary-light);
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
  margin: 20px 0 12px;
}

.image-container {
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.image-container h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}

.plate-img {
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.ocr-actions {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.ocr-result-card {
  margin: 16px auto;
  width: 95%;
  min-height: 56px;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f0f9eb;
  border-radius: 10px;
  border: none;
}

.detection-table {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .result-view {
    padding: 10px;
    gap: 10px;
  }

  .preview-img {
    height: 200px;
  }
}
</style> 